//
//  MCAddFriendSearchViewController.m
//  MicroChat
//
//  Created by Mac on 2018/5/30.
//  Copyright © 2018年 stoneobs.qq.com. All rights reserved.
//

#import "MCAddFriendSearchViewController.h"
#import "MCFriendTableViewCell.h"
@interface MCAddFriendSearchViewController ()<UITextFieldDelegate>
@property(nonatomic, strong) UITextField                     *textFiled;/**< 输入框 */
@property(nonatomic, strong) STButton                        *cancleButton;/**< 取消或者搜索 */
@property(nonatomic, strong) NSMutableArray                     *dataSouce;/**< 搜索数据源 */
@end

@implementation MCAddFriendSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self addNotifacations];
    [self configSubView];
    // Do any additional setup after loading the view.
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(textFiledDidChangeNotifacation:)
                                                 name:UITextFieldTextDidChangeNotification
                                               object:nil];
    
}
- (void)textFiledDidChangeNotifacation:(NSNotification*)notifay{
    if (notifay.object == self.textFiled) {
        [self textFiledDidChange];
    }
}
- (void)textFiledDidChange{
    if (self.textFiled.text.length) {
        [self.cancleButton setTitle:@"搜索" forState:UIControlStateNormal];
    }else{
        [self.cancleButton setTitle:@"取消" forState:UIControlStateNormal];
    }
    if (self.textFiled.text.length) {
        
    }

}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)configSubView{
    UIView * serarchView = [[UIView alloc] initWithFrame:CGRectMake(10, 0, UIScreenWidth - 20, 35)];
    serarchView.backgroundColor = [UIColor whiteColor];
    __weak typeof(self) weakSelf =  self;
    
    STButton * cancleButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 60, 35)
                                                        title:@"取消"
                                                   titleColor:[UIColor whiteColor]
                                                    titleFont:16
                                                 cornerRadius:0
                                              backgroundColor:TM_ThemeBackGroundColor
                                              backgroundImage:nil
                                                        image:nil];
    cancleButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    cancleButton.right =  serarchView.width;
    [cancleButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedButton];
    }];
    self.cancleButton = cancleButton;
    [serarchView addSubview:cancleButton];
    
    STButton * iconButton = [[STButton alloc] initWithFrame:CGRectMake(10, 0, 40, 35)
                                                      title:nil
                                                 titleColor:nil
                                                  titleFont:0
                                               cornerRadius:0
                                            backgroundColor:nil
                                            backgroundImage:nil
                                                      image:[UIImage imageNamed:@"搜索8"]];
    iconButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    
    self.textFiled = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, serarchView.width - cancleButton.width, serarchView.height)];
    self.textFiled.placeholder = @"输入用户名/ID/手机号";
    [serarchView addSubview:self.textFiled];
    self.textFiled.leftView = iconButton;
    self.textFiled.leftViewMode = UITextFieldViewModeAlways;
    self.textFiled.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.textFiled.autocorrectionType =  UITextAutocorrectionTypeNo;
    self.textFiled.autocapitalizationType = UITextAutocapitalizationTypeNone;
    self.textFiled.returnKeyType = UIReturnKeySearch;
    self.textFiled.delegate = self;
    [self.textFiled becomeFirstResponder];
    self.navigationItem.titleView = serarchView;
    
    
    self.tableView.st_noreslutView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, 100, UIScreenWidth, 400) title:@"没有该用户" buttonTitle:@"" buttonHandle:^(NSString *titleString) {
        
    }];

}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return MCFriendTableViewCell.cellHeight;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 24;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    MCFriendTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[MCFriendTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    MCUserModel * user = self.dataSouce[indexPath.row];
    cell.user = user;
    return cell;
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MCUserModel * user = self.dataSouce[indexPath.row];
    [self.textFiled resignFirstResponder];
    [self dismissViewControllerAnimated:YES completion:^{
        if (self.didSelctedSearch) {
            self.didSelctedSearch(user);
        }
    }];
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

#pragma mark --UITextFiledDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    if ([string isEqualToString:@"\n"]) {
        [self onSelctedButton];
        return NO;
    }
    return YES;
}
- (void)onSelctedButton{
    if ([self.cancleButton.currentTitle isEqualToString:@"取消"]) {
        [self dismissViewControllerAnimated:YES completion:nil];
    }else{
        [self sendUserSearchRequest];
    }
}
#pragma mark --NetWork Method
- (void)sendUserSearchRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * paramDic = [NSMutableDictionary new];
    NSString * userID = [STUserManger defult].loginedUser.userID;
    if (userID.length) {
        [paramDic setObject:userID forKey:@"id"];
    }
    if (self.textFiled.text.length) {
         [paramDic setObject:self.textFiled.text forKey:@"search"];
    }
    NSString * url = [NSString stringWithFormat:@"%@%@",releaseServerUrlHeader,@"/Rest/User/searchUsers"];
    DDLogInfo(@"url:%@",url);
    DDLogInfo(@"param:%@",paramDic);
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:paramDic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * modelDic = [responseObject valueForKey:@"data"];
                                                 MCUserModel * user = [MCUserModel mj_objectWithKeyValues:modelDic];
                                                 self.dataSouce = NSMutableArray.new;
                                                 [self.dataSouce addObject:user];
                                                 [self.tableView reloadData];
                                                 DDLogInfo(@"%@请求成功:resp\n%@",url,responseObject);
                                                 
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 DDLogError(@"\nurl:%@\nparam:%@\nreson:%@",url,paramDic,error.desc);
                                             }];
}
@end
